package com.leju.common.lrucache;

import java.io.File;

import com.leju.common.util.Utils.StringUitls;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;

public class PhoneStateUtils {

	private static String TAG = "PhoneStateUtils";

	public static final int WIFI_CONNECT = 0;
	public static final int NO_CONNECT = -1;
	public static final int CM_WAP = 11;
	public static final int CM_NET = 12;
	public static final int WAP_3G = 21;
	public static final int NET_3G = 22;
	public static final int UNI_WAP = 31;
	public static final int UNI_NET = 32;
	public static final int CT_WAP = 41;
	public static final int CT_NET = 42;
	
	private static final    String WIFI = "wifi";
	public static final    String CMWAP = "cmwap"; 
	private static final    String CMNET = "cmnet";
	public static final    String WAP3G = "3gwap"; 
	private static final    String NET3G = "3gnet";
	public static final    String UNIWAP = "uniwap";
	private static final    String UNINET = "uninet";
	public static final    String CTWAP = "ctwap"; 
	private static final    String CTNET = "ctnet";
	
	public static final Uri PREFERRED_APN_URI = 
			Uri.parse("content://telephony/carriers/preferapn");
	
	public static String getIMSI(Context context) {
		TelephonyManager mTelephonyMgr = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		String imsi = mTelephonyMgr.getSubscriberId();		
		if(null == imsi) imsi = "";
		return imsi;
	}

	public static String getIMEI(Context context) {
		TelephonyManager mTelephonyMgr = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		String imei = mTelephonyMgr.getDeviceId();
		return imei;
	}

	public static String getPhoneModel(Context context) {
		String phoneModel = Build.MODEL;
		return phoneModel;
	}

	/**
	 * 
	 * 方法说明：得到版本号
	 *
	 * @param context
	 * @return
	 * @throws NameNotFoundException
	 */
	public static String getAppVersion(Context context)
			throws NameNotFoundException {
		String oldVersion;
		PackageInfo info = context.getPackageManager().getPackageInfo(
				context.getPackageName(), 0);
		oldVersion = info.versionName;
		return oldVersion;
	}

	/**
	 * 
	 * 方法说明：得到版本号
	 *
	 * @param context
	 * @return
	 * @throws NameNotFoundException
	 */
	public static String getAppVersion(Context context, String packageName)
			{
		String oldVersion = "";
		PackageInfo info;
		try {
			info = context.getPackageManager().getPackageInfo(
					packageName, 0);
			oldVersion = info.versionName;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return oldVersion;
	}
	
	/**
	 * 获取当前网络连接，wifi为0，其他为大于0 ；无网络连接时state为-1 *
	 * 
	 * @param context
	 */
	public static int getNetStates(Context context) {
		// 联网方式，0 wifi, 1 3G, 2 cmnet, 3 cmwap
		// 无网络连接时为-1
		int states = 0;

		ConnectivityManager connec = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connec.getActiveNetworkInfo();
		// 获得系统服务，从而取得sim数据
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		// 获得手机SIMType
		int type = (tm == null) ? 0 : tm.getNetworkType();
		if (tm != null)
			if (info != null) {
				if (info.getType() == ConnectivityManager.TYPE_WIFI) {
					states = 0;
				} else {
					if (info.getExtraInfo() != null)
						if (info.getExtraInfo() != null
								&& info.getExtraInfo().toLowerCase()
										.indexOf("wap") != -1) {
							states = 3;
						} else if (info.getExtraInfo() != null
								&& info.getExtraInfo().toLowerCase()
										.equals("cmnet")) {
							states = 2;
						} else {
							// 其它
							states = 1;
						}
				}
			} else {
				// 无网络可用
				states = -1;
			}
		return states;
	}

	/*** 
	    * 判断Network具体类型（联通移动wap，电信wap，其他net） 
	    *    
	    * */ 
	  public static int checkNetworkType(Context mContext) { 
	    try { 
	      final ConnectivityManager connectivityManager = (ConnectivityManager) mContext 
	          .getSystemService(Context.CONNECTIVITY_SERVICE); 
	      final NetworkInfo mobNetInfoActivity = connectivityManager 
	          .getActiveNetworkInfo(); 
	      
	      if (mobNetInfoActivity == null || !mobNetInfoActivity.isAvailable()) { 
	    	  return NO_CONNECT; 
	      } else { 
	          // NetworkInfo不为null开始判断是网络类型 
	    	  int netType = mobNetInfoActivity.getType(); 
	          if (netType == ConnectivityManager.TYPE_WIFI) { 
	        	  //Log.d("", "=====================>wifi network!"); 
	        	  return WIFI_CONNECT; 
	          } else if (netType == ConnectivityManager.TYPE_MOBILE) { 
	        	  Cursor c = null;
	        	  try {
					  c = mContext.getContentResolver().query( 
							  PREFERRED_APN_URI, null, null, null, null); 
					  if (c != null) { 
						  c.moveToFirst(); 
						  final String user = c.getString(c 
								  .getColumnIndex("user")); 
						  if (!TextUtils.isEmpty(user)) { 
							  if (user.startsWith(CTWAP)) { 
								  //Log.d("", "=====================>ctwap network!"); 
								  c.close(); 
								  return CT_WAP; 
							  }else if(user.startsWith(CTNET)) {
								  //Log.d("", "=====================>ctnet network!");  
								  c.close(); 
								  return CT_NET;
							  }
						  } 
					  } 
					  c.close();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally{
					if(null != c && !c.isClosed()){
						c.close();
					}
				}
	          
	        	  String netMode = mobNetInfoActivity.getExtraInfo(); 
	        	  //Log.d(TAG, "netMode ================== " + netMode); 
	        	  if (netMode != null) { 
	        		  // 通过apn名称判断是否是联通和移动wap 
	        		  netMode=netMode.toLowerCase();
	        		  if(netMode.equals(CMWAP)){
	        			  return CM_WAP;
	        		  }else if(netMode.equals(CMNET)){
	        			  return CM_NET;
	        		  }else if(netMode.equals(UNIWAP)){
	        			  return UNI_WAP;
	        		  }else if(netMode.equals(UNINET)){
	        			  return UNI_NET;
	        		  }else if(netMode.equals(NET3G)){
	        			  return NET_3G;
	        		  }else if(netMode.equals(WAP3G)){
	        			  return WAP_3G;
	        		  }else if(netMode.equals(CTWAP)){
	        			  return CT_WAP;
	        		  }else if(netMode.equals(CTNET)){
	        			  return CT_NET;
	        		  }
	        	  } 
	          } 
	      } 
	      } catch (Exception ex) { 
	    	  ex.printStackTrace(); 
	    	  return NO_CONNECT; 
	      } 
	      return NO_CONNECT; 
	}
	  
	/**
	 * 正常返回manifest中的meta-data为channel的value 若没有或为空，则返回null
	 * 
	 * @param context
	 * @return
	 */
	public static String getChannel(Context context) {
		ApplicationInfo ai;
		try {
			ai = context.getPackageManager().getApplicationInfo(
					context.getPackageName(), PackageManager.GET_META_DATA);
			Bundle bundle = ai.metaData;
			Integer param = bundle.getInt("UMENG_CHANNEL");
			String channel = param.toString();
//			int l = 4 - channel.length();
//			for(int i=0; i<l; i++) {//不够四位补零
//				channel = "0" + channel;
//			}
			return channel;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 正常返回manifest中的meta-data为channel的value 若没有或为空，则返回null
	 * 
	 * @param context
	 * @return
	 */
	public static String getChannel(Context context, String packageName) {
		ApplicationInfo ai;
		try {
			ai = context.getPackageManager().getApplicationInfo(
					packageName, PackageManager.GET_META_DATA);
			Bundle bundle = ai.metaData;
			Integer param = bundle.getInt("UMENG_CHANNEL");
			String channel = param.toString();
//			int l = 4 - channel.length();
//			for(int i=0; i<l; i++) {//不够四位补零
//				channel = "0" + channel;
//			}
			return channel;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 获取屏幕大小
	 * 
	 * @param context
	 * @return
	 */
	public static String getScreen(Context context) {
		DisplayMetrics dm = context.getResources().getDisplayMetrics();
		// ((Activity) context).getWindowManager().getDefaultDisplay()
		// .getMetrics(dm);

		String str = dm.widthPixels + "," + dm.heightPixels;
		return str;
	}

	public static String getSDcarPath() {
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
		if (sdCardExist) {
			File sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
			return sdDir.toString();
		}
		return null;
	}
	
	
	public static boolean isCompanyChannel(Context context){
		String currentPackageName = context.getPackageName();
		if(StringUitls.isNotBlank(currentPackageName)){
			if(currentPackageName.indexOf("market") < 0){
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
	
}
